package fr.nantes.univ.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fr.nantes.univ.DAO.AddressBookDAO;
import fr.nantes.univ.DAO.AddressDAO;
import fr.nantes.univ.EntityBeans.Address;
import fr.nantes.univ.EntityBeans.AddressBook;

@SuppressWarnings("serial")
public class AddAddressServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		
		RequestDispatcher rd = request.getRequestDispatcher("/addaddress.jsp");
		rd.forward(request, response);
		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		
		HttpSession session = request.getSession(true);		
		AddressBook addressBook = AddressBookDAO.findById(request.getParameter("address"));
		
		if (addressBook != null) {
			Address address = new Address();
			address.setAddressNumber(Integer.valueOf(addressBook.getNumero()));
			address.setAddress(String.valueOf(request.getParameter("address")));
			address.setPostCode(Integer.valueOf(addressBook.getCodePostal()));
			//address.setCity();
			//address.setNeighborhood();
			address.setRivoliCode(Integer.valueOf(addressBook.getRivoli()));
			address.setLatitude(Double.valueOf(addressBook.getLatitude()));
			address.setLongitude(Double.valueOf(addressBook.getLongitude()));
			address.setUserId(String.valueOf(session.getAttribute("id")));
			AddressDAO.insert(address);
		}
		response.sendRedirect("/myaddresses");
	}

}
